import { Button, Cascader, ConfigProvider, Form, Input, message, Pagination, Popconfirm, Select, Table, type FormProps, type PaginationProps, type TableColumnsType } from "antd";
import '../../assets/css/Building/buildingCss.less'
import zhCN from 'antd/locale/zh_CN';
import { useEffect, useState } from "react";
import type { TableRowSelection } from "antd/es/table/interface";
import { deleteHouse, deleteHouseAll, HouseList } from "../../apis/house";
import type { editFace, HouseListListFace, HouseListParams } from "../../type/house";
import { buildingList } from "../../apis/building";
import { transformBuildingData2 } from "../../utils/tree2";
import AddDiaLog from "../../component/House/DiaLog";
type FieldType = {
    buildingid?: number;
    areas?: number;
    areas2?: number;
    orientation: string;
    type: string;
    houseno: number;
};
interface DataType {
    buildingid?: number
    key: React.Key;
    id: number;
    building: string;
    houseno: string;
    areas: number;
    type: string;
    orientation: string;
}
interface Option {
    value: string;
    label: string;
    children?: Option[];
}
export default function House() {
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [params, setParams] = useState<HouseListParams>({ page: 1, psize: 10 });
    const [total, setTotal] = useState<number>()
    const [ListData, setListData] = useState<HouseListListFace[]>()
    // 楼栋选择框的填充
    const [BuildingData, setBuildingData] = useState<Option[]>()
    // 房型选择框的填充
    const [orientationArray] = useState<string[]>(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']);
    // 朝向选择框的填充
    const [orientationArray2] = useState<string[]>(['朝北', '朝南', '朝西', '朝东', '东北', '东南', '西北', '西南']);
    const [openAdd, setOpenAdd] = useState(false);
    const [editContent, setEditContent] = useState<editFace | null>({ id: 0 });
    const dataSource: DataType[] | undefined = ListData?.map((item) => ({
        key: item.id, // Table组件需要唯一的key
        id: item.id,
        building: item.building,
        buildingid: item.buildingid,
        houseno: item.houseno,
        areas: item.areas,
        type: item.type,
        orientation: item.orientation
    }));
    // 搜索提交
    // 修改onFinish函数
    const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
        // 处理楼栋ID，如果它是数组则取最后一个值
        const processedValues = { ...values };

        // 如果buildingid是数组（来自Cascader），取最后一个值
        if (Array.isArray(values.buildingid)) {
            const buildingArray = values.buildingid as unknown as (string | number)[];
            if (buildingArray.length > 0) {
                processedValues.buildingid = Number(buildingArray[buildingArray.length - 1]);
            }
        }

        // 过滤掉空值
        const filteredValues = Object.fromEntries(
            Object.entries(processedValues).filter(([_, value]) =>
                value !== undefined && value !== null && value !== ''
            )
        );

        setParams({
            ...params,
            ...filteredValues,
            page: 1 // 搜索时重置到第一页
        });
    };
    // 当params更新后 刷新数据
    useEffect(() => {
        getList()
    }, [params])
    // 删除房间
    const del = async (id: number) => {
        let res = await deleteHouse(id)
        if (res.errCode == 10000) {
            message.success('删除成功')
            getList()
        } else {
            message.error('删除失败')
        }
    }
    // 关闭弹窗
    const refresh = () => {
        setOpenAdd(false)
        setEditContent({ ...editContent, id: 0,}); // 重置 id
        getList()
        getBuilding()
    }
    // 表格的渲染
    const columns: TableColumnsType<DataType> = [
        { title: '房间id', dataIndex: 'id', width: 100, align: 'center' },
        { title: '楼号', dataIndex: 'building', align: 'center' },
        { title: '房间号', dataIndex: 'houseno', align: 'center' },
        { title: '面积(平方)', dataIndex: 'areas', align: 'center' },
        { title: '房间类型', dataIndex: 'type', align: 'center' },
        { title: '朝向', dataIndex: 'orientation', align: 'center' },
        {
            title: '操作', dataIndex: 'address', width: 300, align: 'center',
            render: (_, record) => (
                <div style={{ display: 'flex', justifyContent: 'center' }}>-
                    {/* 你可以在这里添加实际的操作按钮 */}
                    <Button variant="solid" onClick={() => {
                        setEditContent({
                            id: record.id,
                            data: {
                                ...record,
                                buildingid: record.buildingid ?? 0 // 提供默认值以确保类型兼容
                            }
                        })
                        setOpenAdd(true)
                    }} color="green" type="primary">修改</Button>
                    <Popconfirm
                        title="提示"
                        description="你确定要删除这条数据吗?"
                        onConfirm={() => { del(Number(record.id)) }}
                        okText="删除"
                        cancelText="取消"
                    >
                        <Button variant="solid" color="red" style={{ marginLeft: '10px' }} type="primary">删除</Button>
                    </Popconfirm>
                </div>
            )
        },
    ];
    // 页面渲染后加载数据
    useEffect(() => {
        getList()
        // 获取搜索项中 楼栋的数据
        getBuilding()
    }, []);
    const getList = async () => {
        let res = await HouseList(params)
        setListData(res.data.list)
        setTotal(res.data.counts)
    }
    const getBuilding = async () => {
        let res = await buildingList()
        setBuildingData(transformBuildingData2(res.data.list))

    }
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection: TableRowSelection<DataType> = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    // 批量删除
    const delAll = async () => {
        let res = await deleteHouseAll(selectedRowKeys as number[])
        if (res.errCode == 10000) {
            message.success('删除成功')
            getList()
        } else {
            message.error('删除失败')
        }
    }
    // 修改分页
    const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
        setParams({ ...params, page: current, psize: pageSize });
    };

    const onChange: PaginationProps['onChange'] = (page, pageSize) => {
        setParams({
            ...params,
            page: page,
            psize: pageSize || params.psize
        });
    };
    return (
        <ConfigProvider locale={zhCN}>
            <div className='ContentBody'>
                <div className="header">
                    <p>房间列表</p>
                </div>
                {/* 搜索 */}
                <div>
                    <Form
                        name="basic"
                        layout="inline"
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        autoComplete="off"
                        style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}
                    >
                        <Form.Item<FieldType>
                            label="楼栋"
                            name="buildingid"
                        >
                            <Cascader
                                options={BuildingData}
                                placeholder="选择小区"
                                fieldNames={{ label: 'label', value: 'value', children: 'children' }}
                                showSearch
                            />
                        </Form.Item>
                        <Form.Item<FieldType>
                            label="房间号"
                            name="houseno"
                        >
                            <Input placeholder="房间号" style={{ width: '100px' }} />
                        </Form.Item>
                        <Form.Item<FieldType>
                            label="房间类型"
                            name="type"
                        >
                            <Select
                                showSearch
                                placeholder="选择类型"
                                optionFilterProp="label"
                                allowClear
                                options={orientationArray.map((item: string) => {
                                    return { value: item + '室', label: item + '室' }
                                })}
                            />
                        </Form.Item>
                        <Form.Item<FieldType>
                            label="面积"
                            name="areas"
                        >
                            <Input style={{ width: '120px' }} />
                        </Form.Item>
                        <Form.Item<FieldType>
                            label="至"
                            name="areas2"
                        >
                            <Input style={{ width: '120px' }} />
                        </Form.Item>
                        <Form.Item<FieldType>
                            label="房间朝向"
                            name="orientation"
                        >
                            <Select
                                showSearch
                                placeholder="选择朝向"
                                optionFilterProp="label"
                                allowClear
                                options={orientationArray2.map((item: string) => {
                                    return { value: item, label: item }
                                })}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                搜索
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
                {/* 按钮 */}
                <div className='AddBtn'>
                    <Button variant="solid" onClick={() => {
                    setOpenAdd(true);
                    setEditContent(null)
                    }} type="primary">添加</Button>
                    <Popconfirm
                        title="提示"
                        description="你确定要删除这些数据吗?"
                        onConfirm={() => { delAll() }}
                        okText="删除"
                        cancelText="取消"
                    >
                        <Button variant="solid" disabled={selectedRowKeys.length ? false : true} color="red" style={{ marginLeft: '10px' }} type="primary">批量删除</Button>
                    </Popconfirm>

                </div>
                {/* 表格 */}
                <Table<DataType> rowSelection={rowSelection} columns={columns} dataSource={dataSource}
                    scroll={{ x: 'max-content' }}
                    tableLayout="auto"
                    style={{ width: '100%' }}
                    pagination={false} // 取消分页
                />
                {/* 分页 */}
                <Pagination
                    showSizeChanger
                    onShowSizeChange={onShowSizeChange}
                    onChange={onChange}
                    current={params.page}
                    pageSize={params.psize}
                    total={total}
                    showTotal={(total) => `共 ${total} 条记录`}
                    showQuickJumper
                />
                {/* 添加与修改 */}
                <AddDiaLog openAdd={openAdd} refresh={refresh} editContent={editContent} />
            </div>
        </ConfigProvider>
    )
}